// files.cpp : Defines the entry point for the console application.
//

#include <Windows.h>
#include <iostream>

int main(int argc, char* argv[])
{

	HANDLE hFile, hAppend;
	DWORD dwBytesRead, dwBytesWritten, dwPos;
	char buff[4096];
	TCHAR szMsg[1000];

	using namespace std;
	cout << "winapi files tests:\n";
	cout << "1) open if existing for read: ";
	hFile = CreateFile (TEXT("\\nonexistent.txt"),    // t
                      GENERIC_READ,           // Open for reading
                      0,                      // Do not share
                      NULL,                   // No security
                      OPEN_EXISTING,          // Existing file only
                      FILE_ATTRIBUTE_NORMAL,  // Normal file
                      NULL);                  // No template file
	cout << (hFile != INVALID_HANDLE_VALUE ? "ok" : "failed") << endl;

	cout << "2) open or create for write: ";
	hAppend = CreateFile (TEXT("\\created.txt"),      // Open Two.txt.
                        GENERIC_WRITE,          // Open for writing
                        0,                      // Do not share
                        NULL,                   // No security
                        OPEN_ALWAYS,            // Open or create
                        FILE_ATTRIBUTE_NORMAL,  // Normal file
                        NULL);                  // No template file

	bool r = (hAppend != INVALID_HANDLE_VALUE);
	cout << (r ? "ok" : "failed") << endl;
	if (r)
	{
		CloseHandle (hFile);            // Close the first file
		return 0;
	}

	// read/write test
	dwPos = SetFilePointer (hAppend, 0, NULL, FILE_END);
	do
	{
		if (ReadFile (hFile, buff, 4096, &dwBytesRead, NULL))
		{
			WriteFile (hAppend, buff, dwBytesRead,
                 &dwBytesWritten, NULL);
		}
	}
	while (dwBytesRead == 4096);

  // Close both files
	CloseHandle (hFile);
	CloseHandle (hAppend);

	return 0;
}

